/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 递归
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function (root) {
    return isValidLevel(root, -Infinity, Infinity)
};

// 入参为每一个节点，返回是否合法
function isValidLevel(root, min, max) {
    // 返回终止条件
    if (root === null) return true
    if (root.val <= min || root.val >= max) return false

    // 只能通过区间去判断，以为子节点的值的限制是通过所有父节点的值得到的
    return isValidLevel(root.left, min, root.val) && isValidLevel(root.right, root.val, max)
}


/**
 * 迭代遍历,中序遍历，二叉搜索树是一个升序数组，一直更新最小值
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function (root) {
    let minNum = -Infinity,
        stack = [];
    while (stack.length > 0 || root !== null) {
        while (root) {
            stack.push(root)
            root = root.left
        }
        let node = stack.pop()
        if(node.val <= minNum){
            return false
        }
        minNum = node.val
        root = node.right
    }
    return true
}